<?php

namespace app\api\controller\User;

use app\services\PaymentService;
use app\services\PropertyService;
use app\services\UpLineService;
use plugin\admin\app\model\User;
use support\Db;
use support\Request;

class PropertyController
{
    public function transfer(Request $request)
    {
        try {
            $mobile = $request->post('mobile');
            $propertyType = $request->post('property_type');
            $amount = $request->post('amount');

            if (!is_numeric($amount) || $amount < 0) {
                throw new \Exception('不正确的金额');
            }

            $user = User::where('mobile', $mobile)->first();
            if (!$user) {
                throw new \Exception('转账用户不存在');
            }

            if (!UpLineService::isSameLine(get_user_id(), $user['id'])) {
                throw new \Exception('不是同一条线，无法互转');
            }

            switch ($propertyType) {
                case 1:
                    $propertyType = 'register_integral';
                    break;
                case 2:
                    $propertyType = 'recharge_integral';
                    break;
                default:
                    throw new \Exception('不存在的资产类型');
            }

            Db::beginTransaction();

            try {
                PaymentService::checkPayPassword($request->post('pay_password'));
                PropertyService::transfer(get_user_id(), $user['id'], $propertyType, $amount);
                Db::commit();

                return ok_rsp('成功');
            } catch (\Exception $e) {
                Db::rollBack();
                throw $e;
            }

        } catch (\Exception $e) {
            return e_rsp($e);
        }
    }

    public static function integralToRegisterIntegral(Request $request)
    {
        try {
            $amount = $request->post('amount');

            if (!is_numeric($amount) || $amount < 0) {
                throw new \Exception('不正确的金额');
            }

            Db::beginTransaction();

            try {
                PaymentService::checkPayPassword($request->post('pay_password'));
                PropertyService::integralToRegisterIntegral($amount);
                Db::commit();

                return ok_rsp('成功');
            } catch (\Exception $e) {
                Db::rollBack();
                throw $e;
            }

        } catch (\Exception $e) {
            return e_rsp($e);
        }
    }
}